package io.github.controller.admin;

import com.google.code.kaptcha.Producer;
import io.github.annotation.Log;
import io.github.annotation.Operate;
import io.github.entity.*;
import io.github.service.*;
import io.github.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.annotation.After;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.transaction.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员登录相关
 */
@RestController
public class SysLoginController extends AbstractController {

    @Resource
    private Producer producer;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysAreaServive sysAreaServive;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysUserLoginLogService sysUserLoginLogService;

    /**
     * 默认访问页面
     *
     * @return String
     */
    @RequestMapping("/admin/")
    public R redirect() {
//        if (ShiroUtils.isLogin()) {
//            return "redirect:/admin/index.html";
//        } else {
//            return "/admin/login";
//        }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        long timeout = session.getTimeout();
        System.out.println(">>>>>timeout:" + timeout);
        return R.error(403, "账号过期，请重新登录");
    }



    /**
     * 管理员首页
     *
     * @return String
     */
//    @RequestMapping("/index.html")
//    public String index(Model model) {
//        model.addAttribute("admin", getAdmin());
//        // 用户菜单列表
//        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getAdminId());
//        model.addAttribute("menuList", menuList);
//        return "/admin/index";
//    }

    /**
     * 管理员验证码
     *
     * @throws ServletException
     * @throws IOException
     */
//    @RequestMapping("/captcha.jpg")
//    public void captcha(HttpServletResponse response) throws ServletException, IOException {
//        response.setHeader("Cache-Control", "no-store, no-cache");
//        response.setContentType("image/jpeg");
//
//        // 生成文字验证码
//        String text = producer.createText();
//        // 生成图片验证码
//        BufferedImage image = producer.createImage(text);
//        // 保存到shiro session
//        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
//
//        ServletOutputStream out = response.getOutputStream();
//        ImageIO.write(image, "jpg", out);
//    }

    @RequestMapping(value = "/admin/sys/relogin",method = RequestMethod.GET)

    public R relogin(){
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        return R.error(403,"账号过期，请重新登录");
    }

    /**
     * 管理员登录
     *
     * @return Map
     * @throws IOException
     */

    @RequestMapping(value = "/admin/sys/login", method = RequestMethod.POST)
    @Transactional(rollbackOn = Exception.class)
    public R login(@RequestBody SysUserEntity enti, HttpServletRequest request) throws IOException {
        logger.info("用户登录接口");
        if (StringUtils.isBlank(enti.getUsername())) {
            return R.error(500, "请输入用户名！");
        }
        if (StringUtils.isBlank(enti.getPassword())) {
            return R.error(500, "请输入密码！");
        }
        try {
            Subject subject = ShiroUtils.getSubject();
            // sha256加密
            String password = new Sha256Hash(enti.getPassword()).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(enti.getUsername(), password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error(e.getMessage());
        } catch (LockedAccountException e) {
            return R.error(e.getMessage());
        } catch (AuthenticationException e) {
            return R.error(500, "账户验证失败");
        }
        //当前登录用户
        SysUserEntity user = getAdmin();
        //当前登录用户id
        Long userId = getAdminId();
        // 登录IP
        String ipAddress = GetIpAddress.getIpAddress(request);
        // 当前时间戳
        Long currentUnixTime = DateUtils.getCurrentUnixTime();
        user.setLastLoginIp(ipAddress);
        //user.setLastLoginTime(currentUnixTime);
        boolean updateById = sysUserService.updateById(user);
        if (!updateById) {
            return R.error("系统异常，请联系管理员!");
        }
        // 记录登录日志
        SysUserLoginLogEntity entity = new SysUserLoginLogEntity();
        entity.setBrowser(HttpUtil.getUserBrowser(request));
        entity.setLoginTime(currentUnixTime);
        entity.setOperatingSystem(HttpUtil.getUserOperatingSystem(request));
        entity.setUserId(getAdminId());
        entity.setLoginIp(ipAddress);
        boolean insert = sysUserLoginLogService.insert(entity);

        // 这里只能抛异常回滚事务
        if (!insert) {
            throw new RRException("系统异常，请联系管理员!");
        }
        SysUserEntity userEntity = new SysUserEntity();
        String areaid = user.getAreaid();
        //地区id数组
        String[] split = areaid.split(",");

        //获取菜单id及名称
        List<String> roleNameList = sysUserRoleService.queryRoleNames(userId);
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        System.out.println(">>>>>roleIdList:" + roleIdList);
        List<Long> menuIdList = new ArrayList<Long>();
        for (int i = 0; i < roleIdList.size(); i++) {
            Long roleId = roleIdList.get(i);
            menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
            System.out.println(">>>>>list:" + menuIdList);
        }
        List<String> nameList = new ArrayList<String>();
        //获取地区id对应地区名称
        for (String aId : split) {
            SysAreaEntity sysAreaEntity = sysAreaServive.selectById(aId);
            nameList.add(sysAreaEntity.getName());
        }

        userEntity.setNameList(nameList);
        userEntity.setUsername(user.getUsername());
        userEntity.setUserId(user.getUserId());
        userEntity.setAreaid(user.getAreaid());
        userEntity.setEmail(user.getEmail());
        userEntity.setMobile(user.getMobile());
        userEntity.setNickname(user.getNickname());
        userEntity.setRoleIdList(roleIdList);
        userEntity.setRoleNameList(roleNameList);
        userEntity.setMenuIdList(menuIdList);

        logger.info("user:" + userEntity);

        return R.ok().put("user", userEntity);
    }


    /**
     * 管理员退出
     *
     * @return String
     * @throws Exception
     */
    @Log(value = "用户退出了",action = 9)
    @RequestMapping(value = "/admin/sys/logout", method = RequestMethod.GET)
    public R logout() {
        logger.info("用户退出接口");
        if (ShiroUtils.isLogin()) {
            String cacheName = EhCacheNames.MENUCACHENAME + ShiroUtils.getUserId();
            ehcacheUtil.remove(EhcacheUtil.ADMINMENUEHCACHENAME, cacheName);
            logger.info("管理员退出，清空用户菜单列表Cache");
            Long userId = ShiroUtils.getUserId();
            // 系统管理员退出
            if (userId != null && userId.equals(Long.valueOf(constant.adminId))) {
            }
            ShiroUtils.logout();
        }

        return R.ok();
    }


}
